package com.atguigu.tingshu.order.interceptor.impl;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;

// 表单重复校验任务类
@Service
@Slf4j
public class OrderRepeatSbumitValidOrderHandlerInterceptor implements OrderHandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public OrderInfoVo sbumitOrderRequestProcess(OrderInfoVo orderInfoVo) {
        log.info("OrderRepeatSbumitValidOrderHandlerInterceptor....");

        // 表单重复提交校验
        String tradeNo = orderInfoVo.getTradeNo();
        if (StringUtils.isEmpty(tradeNo)){
            throw  new GuiguException(ResultCodeEnum.ILLEGAL_REQUEST);      //  非法提交
        }

        String script = "if(redis.call('exists', KEYS[1])) then return redis.call('del', KEYS[1]) else return 0 end" ;

        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(RedisConstant.ORDER_TRADE_NO + tradeNo));
        if (result ==0){
            throw new GuiguException(ResultCodeEnum.ORDER_SUBMIT_REPEAT);   // 表单重复提交了
        }

        return orderInfoVo;

    }

    @Override
    public int sort() {
        return 2;
    }
    
}